package com.likersai.opon.service.impl;

import com.likersai.opon.pojo.entity.Menu;
import com.likersai.opon.pojo.bo.MenuTreeModel;
import com.likersai.opon.pojo.bo.PageBO;
import com.likersai.opon.dao.MenuMapper;
import com.likersai.opon.pojo.dto.param.menu.MenuSelect;
import com.likersai.opon.pojo.vo.req.menu.AddMenuReq;
import com.likersai.opon.pojo.vo.req.menu.ModMenuReq;
import com.likersai.opon.service.MenuService;
import com.likersai.opon.service.param.menu.MenuQuery;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 菜单服务类实现
 *
 * @author sun.ye
 * @since 2021-03-14 00:23
 */
@Service
public class MenuServiceImpl implements MenuService {


    private final MenuMapper menuMapper;

    public MenuServiceImpl(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    public List<MenuTreeModel> queryMenuTree(MenuQuery param) {
        List<MenuTreeModel> menuTree = new ArrayList<>();
        List<Menu> menuList = menuMapper.selectMenu(param.toMenuQuery());
        ListIterator<Menu> iterator = menuList.listIterator();
        Map<Long, MenuTreeModel> dictionary = new HashMap<>();
        while (iterator.hasNext()){
            Menu menuItem = iterator.next();
            MenuTreeModel treeModelItem = MenuTreeModel.instanceFrom(menuItem);
            dictionary.put(menuItem.getId(),treeModelItem);
            Long parentId = menuItem.getParentId();
            if (parentId == 0L){
                menuTree.add(treeModelItem);
            }else {
                dictionary.get(parentId).addChildren(treeModelItem);
            }
        }
        return menuTree;
    }

    @Override
    public List<Menu> queryMenu(MenuQuery param) {
        return menuMapper.selectMenu(param.toMenuQuery());
    }

    @Override
    public PageBO<Menu> queryMenuPage(MenuQuery param) {
        MenuSelect menuSelect = param.toMenuQuery();
        List<Menu> rows = menuMapper.selectMenu(menuSelect);
        PageBO<Menu> page = new PageBO<>();
        page.setTotalCount(menuMapper.countAll(menuSelect));
        page.setRows(rows);
        page.setPageNum(param.getPageNum());
        page.setPageSize(param.getPageSize());
        return page;
    }

    @Override
    public Menu addMenu (AddMenuReq req) {
        Menu record = req.toEntity();
        menuMapper.insertMenu(record);
        return record;
    }
    
    @Override
    public Integer modMenu (ModMenuReq req) {
        Menu record = req.toEntity();
        return menuMapper.updateMenu(record);
    }
}